#!/bin/bash

echo "======================================"
echo "BPG 前端系统启动脚本"
echo "======================================"
echo ""

# 检查是否在正确的目录
if [ ! -f "bpg.pyc" ]; then
    echo "错误: 请在 bid-proprosal-gen 根目录下运行此脚本"
    exit 1
fi

# 检查 Python
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到 Python3, 请先安装 Python3"
    exit 1
fi

# 检查 Node.js
if ! command -v node &> /dev/null; then
    echo "错误: 未找到 Node.js, 请先安装 Node.js"
    exit 1
fi

# 安装后端依赖
echo "1. 安装后端依赖..."
cd backend
if [ ! -d "venv" ]; then
    echo "   创建 Python 虚拟环境..."
    python3 -m venv venv
fi

echo "   激活虚拟环境并安装依赖..."
source venv/bin/activate
pip install -r requirements.txt -q

# 启动后端服务
echo ""
echo "2. 启动后端服务..."
echo "   后端地址: http://localhost:5000"
python app.py &
BACKEND_PID=$!
echo "   后端进程 PID: $BACKEND_PID"

# 安装前端依赖
echo ""
echo "3. 安装前端依赖..."
cd ../frontend
if [ ! -d "node_modules" ]; then
    echo "   首次安装, 可能需要几分钟..."
    npm install
else
    echo "   依赖已存在, 跳过安装"
fi

# 启动前端服务
echo ""
echo "4. 启动前端开发服务器..."
echo "   前端地址: http://localhost:5173"
echo ""
echo "======================================"
echo "启动完成!"
echo "======================================"
echo "前端: http://localhost:5173"
echo "后端: http://localhost:5000"
echo ""
echo "按 Ctrl+C 停止服务"
echo "======================================"
echo ""

npm run dev

# 清理后端进程
kill $BACKEND_PID 2>/dev/null
